//
//  GLPlaceholderTextView.m
//  GLFormKitDemo
//
//  Created by 121 on 2016/4/18.
//  Copyright © 2018年 杭州吉利控股信息中心. All rights reserved.
//

#import "GLPlaceholderTextView.h"

@implementation GLPlaceholderTextView

- (UILabel *)placeholderLabel
{
    if (_placeholderLabel == nil) {
        UILabel *label = [[UILabel alloc] init];
        //可以自动换行
        //        label.numberOfLines = 0;
        CGRect frame = label.frame;
        frame.origin.x = 4;
        frame.origin.y = 7;
        label.frame =frame;
        _placeholderLabel = label;
        [self addSubview:label];
    }
    return _placeholderLabel;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        [self setUp];
    }
    return self;
}

- (void)awakeFromNib
{
    [super awakeFromNib];
    [self setUp];
}

- (void)setUp
{
    //设置垂直方向永远有弹簧效果    textView继承自UIScrollView，有滚动效果
    self.alwaysBounceVertical = YES;
    
    //设置一些默认的一些属性
    self.font = [UIFont systemFontOfSize:15];
    
    self.placeholderColor = [UIColor grayColor];
    
    //监听textView中文本的输入，用系统自动发出的通知，这里只要添加一个observer就可以
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChange) name:UITextViewTextDidChangeNotification object:nil];
}

/**
 *  控制器销毁的时候，要清楚这个地方的通知observer
 */
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


- (void)textChange
{
    self.placeholderLabel.hidden = self.hasText;
    
}

/**
 * 更新占位文字的尺寸
 */
- (void)updatePlaceholderLabelSize
{
    //CGSize maxSize = CGSizeMake(SCREEN_WIDTH - 2 * self.placeholderLabel.origin.x, MAXFLOAT);
    //    self.placeholderLabel.size = [self.placeholder boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : self.font} context:nil].size;
    [self.placeholderLabel sizeToFit];
}

#pragma mark - 重写setter
- (void)setPlaceholderColor:(UIColor *)placeholderColor
{
    _placeholderColor = placeholderColor;
    
    self.placeholderLabel.textColor = placeholderColor;
}

- (void)setPlaceholder:(NSString *)placeholder
{
    _placeholder = [placeholder copy];
    
    self.placeholderLabel.text = placeholder;
    
    [self updatePlaceholderLabelSize];
}

- (void)setPlaceHolderLabelFont:(UIFont *)placeHolderLabelFont
{
    _placeHolderLabelFont = placeHolderLabelFont;
    self.placeholderLabel.font = placeHolderLabelFont;
    [self updatePlaceholderLabelSize];
}

- (void)setText:(NSString *)text
{
    [super setText:text];
    [self textChange];
}

- (void)setAttributedText:(NSAttributedString *)attributedText
{
    [super setAttributedText:attributedText];
    [self textChange];
}

/**
 *  设置占位文字label的左边距
 */
- (void)setLeftMargin:(CGFloat)leftMargin
{
    _leftMargin = leftMargin;
    CGRect frame = self.placeholderLabel.frame;
    frame.origin.x = leftMargin;
    self.placeholderLabel.frame = frame;
    //self.placeholderLabel.x = leftMargin;
}



@end
